package com.bidepan.spring6.resource;

import org.springframework.core.io.UrlResource;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

public class UrlResourceDemo {
    //访问前缀http，file
    public static void loadUrlResource(String path){
        try {
            UrlResource url = new UrlResource(path);
            //获取资源信息
            System.out.println(url.getFilename());
            System.out.println(url.getURI());
            System.out.println(url.getDescription());
            //文件内容
            try {
                InputStream in = url.getInputStream();
                int available = in.available();
                System.out.println("Available bytes: " + available);
                byte[] bytes = new byte[available];
                while(in.read(bytes) != -1){
                    System.out.println(new String(bytes));
                }
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        loadUrlResource("http://www.baidu.com");
        System.out.println("--------------------------------");
        loadUrlResource("file:myTxt.txt");
    }
}
